<template>
  <div class="app-container">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="检验单编号" prop="iqcCode">
            <el-input v-model="form.iqcCode" readonly placeholder="请输入来料检验单编号"/>
          </el-form-item>
        </el-col>
        <el-col :span="9">
          <el-form-item label="检验单名称" prop="iqcName">
            <el-input v-model="form.iqcName" placeholder="请输入内容"/>
          </el-form-item>
        </el-col>
        <el-col :span="3" align="middle">
          <el-image fit="contain" v-if="form.checkResult == 'ACCEPT'" :src="acceptImg"/>
          <el-image fit="contain" v-else-if="form.checkResult == 'REJECT'" :src="rejectImg"/>
          <el-image fit="contain" v-else :src="prepareImg"/>
        </el-col>
      </el-row>
      <el-divider content-position="center">物料与供应商</el-divider>
      <el-row>
        <el-col :span="8">
          <el-form-item label="产品物料编码" prop="itemCode">
            <el-input v-model="form.itemCode" readonly >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="产品物料名称" prop="itemName">
            <el-input v-model="form.itemName" readonly="readonly"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="单位" prop="unitOfMeasure">
            <el-input v-model="form.unitOfMeasure" readonly="readonly"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="品牌" prop="itemBrand">
            <el-input v-model="form.itemBrand" readonly="readonly"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="颜色" prop="itemColor">
            <el-input v-model="form.itemColor" readonly="readonly"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="技术要求" prop="itemTechReq">
            <el-input v-model="form.itemTechReq" readonly="readonly"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="型号" prop="itemModel">
            <el-input v-model="form.itemModel" readonly placeholder="请选择供应商" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="到货单号" prop="sourceDocCode">
            <el-input v-model="form.sourceDocCode" readonly />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="供应商编码" prop="vendorCode">
            <el-input v-model="form.vendorCode" readonly placeholder="请选择供应商" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="供应商名称" prop="vendorName">
            <el-input v-model="form.vendorName" readonly="readonly"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-divider content-position="center" v-if="drawingList.length>0">图纸信息</el-divider>
      <el-row style="margin-bottom: 50px">
        <el-table :data="drawingList" :cell-style="{'padding':'0px'}"  max-height="400" v-if="drawingList.length>0">
          <el-table-column label="图纸名称" align="center" prop="drawingName">
            <template slot-scope="scope">
              <el-link :underline="false" :href="scope.row.drawingUrl" target="_blank">
                <span class="el-icon-document" style="color: #1890ff;"> {{scope.row.drawingName}}</span>
              </el-link>
            </template>
          </el-table-column>
          <el-table-column label="图号" align="center" prop="drawingCode" />
          <el-table-column label="图纸描述" align="center" prop="remark"/>
        </el-table>
      </el-row>
      <el-divider content-position="center">检测情况</el-divider>
      <el-row>
        <el-col :span="8">
          <el-form-item label="本次接收数量" prop="quantityRecived">
            <el-input v-model="form.quantityRecived" readonly/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="本次检测数量" prop="quantityCheck" >
            <el-input-number type="number" :min="1" v-model="form.quantityCheck" :max=" Number(form.quantityRecived)" :step="0.01" placeholder="请输入本次检测数量"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="不合格数量" prop="quantityUnqualified">
            <el-input-number type="number" :min="0" v-model="form.quantityUnqualified" :max="Number(form.quantityCheck)" :step="0.01" placeholder="请输入不合格数"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="来料日期" prop="reciveDate">
            <el-date-picker clearable
                            v-model="form.reciveDate"
                            type="date"
                            value-format="yyyy-MM-dd"
                            placeholder="请选择来料日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="检测日期" prop="inspectDate">
            <el-date-picker clearable
                            v-model="form.inspectDate"
                            type="date"
                            value-format="yyyy-MM-dd"
                            placeholder="请选择检测日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="检测结果" prop="checkResult">
            <el-select v-model="form.checkResult" placeholder="请选择检测结果">
              <el-option
                v-for="dict in dict.type.mes_qc_result"
                v-if="dict.value!='EXEMPT'"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="检测人员" prop="inspector">
            <el-input v-model="form.inspector" placeholder="请输入检测人员" readonly>
              <el-button slot="append" @click="handleSelectUser" icon="el-icon-search"></el-button>
            </el-input>
            <UserSelect ref="userSelect" @onSelected="onUserSelected" ></UserSelect>
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-divider content-position="center">统计结果</el-divider>
        <el-row>
          <el-col :span="8">
            <el-form-item label="致命缺陷率" prop="crRate">
              <el-input v-model="form.crRate" readonly="readonly"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="严重缺陷率" prop="majRate">
              <el-input v-model="form.majRate" readonly="readonly"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="轻微缺陷率" prop="minRate">
              <el-input v-model="form.minRate" readonly="readonly"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="致命缺陷数量" prop="crQuantity">
              <el-input v-model="form.crQuantity" readonly="readonly"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="严重缺陷数量" prop="majQuantity">
              <el-input v-model="form.majQuantity" readonly="readonly"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="轻微缺陷数量" prop="minQuantity">
              <el-input v-model="form.minQuantity" readonly="readonly"/>
            </el-form-item>
          </el-col>
        </el-row>
      <el-divider v-if="form.iqcId !=null" content-position="center">检测项</el-divider>
      <el-card shadow="always" v-if="form.iqcId !=null" class="box-card">
        <IqcLine ref=line :iqcId="form.iqcId" @handleReview="handleReview"></IqcLine>
      </el-card>
      <el-divider v-if="form.iqcId !=null" content-position="center">检测过程</el-divider>
      <el-card shadow="always" v-if="form.iqcId != null" class="box-card">
<!--        <template v-if="form.attr2">-->
<!--          <a :href="form.attr2" target="_blank">查看文件</a>-->
<!--          <el-button type="text" @click="handleDeleteFile" style="margin-left: 10px;">删除</el-button>-->
<!--        </template>-->
<!--        <template v-else>-->
          <FileUpload
            :limit="5"
            :fileSize="100"
            :fileType="fileType"
            :value="fileList"
            :optType="optType"
            @onUploaded="handleUploaded"
            @onRemoved="handleRemoved">
          </FileUpload>
<!--        </template>-->
      </el-card>
    </el-form>
    <el-form label-width="100px">
      <el-form-item style="text-align: center;margin-left:-120px;margin-top:30px;">
        <el-button type="primary" @click="cancel" v-if=" form.status !='PREPARE' ">返回</el-button>
        <el-button type="primary" @click="submitForm" v-if="form.status =='PREPARE' ">保 存
        </el-button>
        <el-button type="success" @click="handleFinish"
                   v-if="form.status =='PREPARE' && form.iqcId !=null">完成
        </el-button>
        <el-button @click="cancel">取 消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import {listIqc, getIqc, delIqc, addIqc, updateIqc, getQcIqcBySource} from "@/api/mes/qc/iqc";
import IqcLine from "../iqc/iqcline.vue";
import {genCode} from "@/api/system/autocode/rule"
import UserSelect from "@/components/userSelect/single.vue";
import { getUserProfile } from "@/api/system/user";
import {getDrawingByArrivedLineId} from "@/api/mes/cg/drawing"
import {number} from "echarts/lib/export";
export default {
  name: "pendingIqc",
  components: { IqcLine, UserSelect },
  dicts: ['mes_ipqc_type', 'mes_qc_result', 'mes_order_status'],
  data() {
    return {

      acceptImg: require('@/assets/images/accept.png'),
      rejectImg: require('@/assets/images/reject.png'),
      prepareImg: require('@/assets/images/prepare.png'),
      // 表单参数
      form: {},
      // 查看开关
      optType: undefined,
      // 上传文件类型
      fileType: ["pdf","doc", "xls","jpg","png"],
      // 上传文件列表
      fileList: [],
      drawingList:[],
      // 表单校验
      rules: {
        iqcCode: [
          {required: true, message: "请输入或生成检验单编号", trigger: "blur"}
        ],
        quantityRecived: [
          {required: true, message: "本次接收数量不能为空", trigger: "blur"}
        ],
        quantityCheck: [
          {required: true, message: "本次检测数量不能为空", trigger: "blur"}
        ],
        inspectDate: [
          {required: true, message: "检测日期不能为空", trigger: "blur"}
        ],


      },
      // 当前登录用户
      user: null,
    }
  },
  created() {
    this.reset();
    if(this.$route.params.sourceDocId) {
      getQcIqcBySource({
        sourceDocId: this.$route.params.sourceDocId,
        sourceDocCode: this.$route.params.sourceDocCode,
        sourceLineId: this.$route.params.sourceLineId
      }).then(response => {
        if (response.data) {
          this.form = response.data;
          if (!this.form.iqcCode) {
            genCode('QC_IQC_CODE').then(response => {
              this.form.iqcCode = response;
            });
          }
          this.form.quantityRecived = Number(this.$route.params.quantityUncheck);
          this.getDrawingList();
        } else {
          this.reset();
          genCode('QC_IQC_CODE').then(response => {
            this.form.iqcCode = response;
          });
          this.getDrawingList();
        }

      })
    }
  },
  methods: {
    // 取消按钮
    cancel() {
      const obj = {path: "/mes/qc/pendinginspect"};
      this.$tab.closeOpenPage(obj);
    },
    handleReview() {
      getIqc(this.form.iqcId).then(response => {
        this.form.crRate=response.data.crRate;
          this.form.majRate=response.data.majRate;
          this.form.minRate=response.data.minRate;
          this.form.crQuantity=response.data.crQuantity;
          this.form.majQuantity=response.data.majQuantity;
          this.form.minQuantity=response.data.minQuantity;
          response.data.attr2 === null ? this.fileList = [] : this.fileList = response.data.attr2.split(',');
      });
    },
    // 表单重置
    reset() {
      this.form = {
        iqcId: null,
        iqcCode: null,
        iqcName: null,
        templateId: null,
        sourceDocId: this.$route.params.sourceDocId,
        sourceDocType: this.$route.params.sourceDocType,
        sourceDocCode: this.$route.params.sourceDocCode,
        sourceLineId: this.$route.params.sourceLineId,
        vendorId: this.$route.params.vendorClientId,
        vendorCode: this.$route.params.vendorClientCode,
        vendorName: this.$route.params.vendorClientName,
        vendorNick: this.$route.params.vendorClientNick,
        vendorBatch: this.$route.params.batchCode,
        itemId: this.$route.params.itemId,
        itemCode: this.$route.params.itemCode,
        itemName: this.$route.params.itemName,
        specification: this.$route.params.specification,
        unitOfMeasure: this.$route.params.unitOfMeasure,
        itemBrand: this.$route.params.itemBrand,
        itemColor: this.$route.params.itemColor,
        itemTechReq: this.$route.params.itemTechReq,
        itemModel: this.$route.params.itemModel,
        quantityMinCheck: null,
        quantityMaxUnqualified: null,
        quantityRecived: Number(this.$route.params.quantityUncheck),
        quantityCheck: null,
        quantityUnqualified: null,
        crRate: null,
        majRate: null,
        minRate: null,
        crQuantity: null,
        majQuantity: null,
        minQuantity: null,
        checkResult: null,
        reciveDate: this.$route.params.recordTime,
        inspectDate: null,
        inspector: null,
        status: "PREPARE",
        remark: null,
        attr1: null,
        attr2: null,
        attr3: null,
        attr4: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
      this.getUser();
      this.fileList = [];
      this.drawingList=[];
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if(this.form.quantityRecived<this.form.quantityCheck){
            this.$modal.msgError("检测数量不能大于接收数量！");
            return;
          }
          if(this.form.quantityCheck<this.form.quantityUnqualified){
            this.$modal.msgError("不合格数量不能大于检测数量！");
            return;
          }
          if (this.form.iqcId != null) {
            updateIqc(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
            });
          } else {
            addIqc(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.form.iqcId = response.data;
            });
          }
        }
      });
    },
    //点击完成
    handleFinish() {
      let that = this;
      if (this.form.checkResult == null) {
        this.$modal.msgError("请选择检测结果！");
        return;
      }
      if(this.form.quantityRecived<this.form.quantityCheck){
        this.$modal.msgError("检测数量不能大于接收数量！");
        return;
      }
      if(this.form.quantityCheck<this.form.quantityUnqualified){
        this.$modal.msgError("不合格数量不能大于检测数量！");
        return;
      }
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.$modal.confirm('是否完成来料检验单编制？【完成后将不能更改】').then(function () {
            that.form.status = 'FINISHED';
            that.submitForm();
            that.cancel();
          });
        }
      });
    },

    handleSelectUser(){
      this.$refs.userSelect.showFlag = true;
    },
    // 用户选择弹出框
    onUserSelected(obj){
      if(obj != undefined && obj != null){
        this.form.inspector = obj.nickName;
      }
    },
    // 获取登录用户
    getUser() {
      getUserProfile().then(response => {
        this.user = response.data;
        this.form.inspector = this.user.nickName;
      });
    },
    handleDeleteFile() {
      this.form.attr2 = null;
      this.fileList = [];
      this.optType = 'add';
    },
    handleUploaded(data) {
      this.form.attr2 = data;
      this.optType = 'add';
    },
    handleRemoved(data) {
      this.form.attr2 = data;
      this.optType = 'add';
    },
    getDrawingList() {
      getDrawingByArrivedLineId(this.form.sourceLineId).then(response => {
        if(response.data){
          console.log(response.data)
          this.drawingList = response.data;
        }else{
          this.drawingList = [];
        }

      })
    },
  },
  // watch: {
  //   'form.attr2': function (newValue) {
  //     if (newValue) {
  //       this.optType = 'view';
  //     } else {
  //       this.optType = 'add';
  //     }
  //   }
  // },
}


</script>
<style lang="scss" scoped>
.el-divider--horizontal{
  height: 2px;
  background-color: #b2b4b9;
}
</style>
